//
//  UIImage+Extension.m
//  MiguFramework
//
//  Created by Victor Chee on 16/5/11.
//  Copyright © 2016年 Migu. All rights reserved.
//

#import "UIImage+Extension.h"

@implementation UIImage(Extension)

- (UIImage *)imageWithTintColor:(UIColor *)tintColor {
	return [self imageWithTintColor:tintColor blendMode:kCGBlendModeDestinationIn];
}

- (UIImage *)imageWithGradientTintColor:(UIColor *)tintColor {
	return [self imageWithTintColor:tintColor blendMode:kCGBlendModeOverlay];
}

- (UIImage *)imageWithTintColor:(UIColor *)tintColor blendMode:(CGBlendMode)blendMode {
	// We want to keep alpha, set opaque to NO; Use 0.0f for scale to use the scale factor of the
	// device’s main screen.
	UIGraphicsBeginImageContextWithOptions (self.size, NO, 0.0f);
	[tintColor setFill];
	CGRect bounds = CGRectMake (0, 0, self.size.width, self.size.height);
	UIRectFill (bounds);

	// Draw the tinted image in context
	[self drawInRect:bounds blendMode:blendMode alpha:1.0f];

	if (blendMode != kCGBlendModeDestinationIn) {
		[self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
	}

	UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext ();
	UIGraphicsEndImageContext ();

	return tintedImage;
}

- (UIImage *)resize:(CGSize)size {
	UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
	[self drawInRect:CGRectMake (0, 0, size.width, size.height)];
	UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return newImage;
}

- (UIImage *)roundCorner:(CGFloat)radius {
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
    [[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius] addClip];
    [self drawInRect:rect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (UIImage *)addWatermark:(NSString *)text atRect:(CGRect)rect {
    UIGraphicsBeginImageContext(self.size);
    [self drawInRect:CGRectMake (0, 0, self.size.width, self.size.height)];
    
    // Draw watermark
    [[UIColor darkGrayColor] set];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentCenter;
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:10], NSParagraphStyleAttributeName: paragraphStyle};
    [text drawInRect:rect withAttributes:attributes];
    
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return result;
}

- (UIColor *)averageColor {
    // 第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大
    CGSize thumbSize=CGSizeMake(50, 50);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 thumbSize.width,
                                                 thumbSize.height,
                                                 8,//bits per component
                                                 thumbSize.width*4,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedLast);
    
    CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
    CGContextDrawImage(context, drawRect, self.CGImage);
    CGColorSpaceRelease(colorSpace);
    
    // 第二步 取每个点的像素值
    unsigned char* data = CGBitmapContextGetData(context);
    if (data == NULL) {
        CGContextRelease(context);
        return nil;
    }
    NSCountedSet *cls=[NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
    
    for (int x=0; x<thumbSize.width; x++) {
        for (int y=0; y<thumbSize.height; y++) {
            int offset = 4*(x*y);
            
            int red = data[offset];
            int green = data[offset+1];
            int blue = data[offset+2];
            int alpha =  data[offset+3];
            
            NSArray *clr=@[@(red),@(green),@(blue),@(alpha)];
            [cls addObject:clr];
            
        }
    }
    CGContextRelease(context);
    
    // 第三步 计算RGBA各自的总值
    NSEnumerator *enumerator = [cls objectEnumerator];
    NSArray *curColor = nil;
    
    NSInteger maxRed = 0, maxGreen = 0, maxBlue = 0, maxAlpha = 0;
    while ((curColor = [enumerator nextObject]) != nil) {
        maxRed += [curColor[0] integerValue];
        maxGreen += [curColor[1] integerValue];
        maxBlue += [curColor[2] integerValue];
        maxAlpha += [curColor[3] integerValue];
    }
    
    NSInteger count = cls.count;
    return [UIColor colorWithRed:(maxRed/count/255.0f) green:(maxGreen/count/255.0f) blue:(maxBlue/count/255.0f) alpha:(maxAlpha/count/255.0f)];
}

+ (UIImage *)imageWithColor:(UIColor *)color {
    return [self imageWithColor:color size:CGSizeMake(1.0, 1.0)];
}

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

+ (UIImage *)grayImage:(UIImage *)sourceImage
{
    int bitmapInfo = kCGImageAlphaNone;
    int width = sourceImage.size.width;
    int height = sourceImage.size.height;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate (nil,width,height,8,0,colorSpace,bitmapInfo);
    CGColorSpaceRelease(colorSpace);
    if (context == NULL) {
        return nil;
    }
    CGContextDrawImage(context,CGRectMake(0, 0, width, height), sourceImage.CGImage);
    CGImageRef cgImage = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    UIImage *grayImage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    return grayImage;
}

@end
